let {userList,houseData} =require('./src/mock')

const bodyParser=require('body-parser')

const jwt =require('jsonwebtoken')

let authNum=0

module.exports={
    devServer:{
        before:app=>{
            app.use(bodyParser.json())
            app.post('/api/getAuthCode',(req,res)=>{
                authNum=Math.floor(Math.random()*(9999-1000+1)+1000)
                res.send({
                    code:0,
                    data:authNum
                })
            })
            app.post('/api/login',(req,res)=>{
                const {
                    username,
                    password,
                    authCode
                }=req.body
                if(authNum!==authCode){
                    res.send({
                        code:1,
                        msg:'验证码错误'
                    })
                }else if(userList.some(item=>item.username===username&&item.password===password)){
                    const name=userList.find(item=>item.username===username&&item.password===password).name
                    const num=jwt.sign(name,'1906A')
                    res.send({
                        code:0,
                        msg:'登录成功',
                        data:num
                    })
                }else{
                    res.send({
                        code:1,
                        msg:'账号或密码错误'
                    })
                }
            })
            app.post('/api/userinfo',(req,res)=>{
                const {authorization}=req.headers
                const name=jwt.verify(authorization,'1906A')
                const userInfo={...userList.find(item=>item.name===name)}
                delete userInfo.password
                res.send({
                    code:0,
                    data:userInfo
                })
            })
            app.post('/api/gethouselist',(req,res)=>{
                const {pageSize,pageIndex}=req.body
                const list=houseData.filter((item,index)=>{
                    return(pageIndex-1)*pageSize<=index&&index<=pageIndex*size-1
                })
                res.send({
                    code:200,
                    data:{
                        list:list,
                        total:houseData.legth
                    }
                })
            })
        }
    }
}